# coding:utf-8
import os
import sys

from PySide6.QtCore import Qt, QTranslator
from PySide6.QtGui import QFont
from PySide6.QtWidgets import QApplication, QMessageBox
from PySide6.QtNetwork import QLocalServer, QLocalSocket
from qfluentwidgets import FluentTranslator

from app.common.config import cfg

from app.view.main_window import MainWindow


def is_running():
    """检查应用是否已经在运行"""
    try:
        socket = QLocalSocket()
        socket.connectToServer("ZToughAI")
        is_running = socket.waitForConnected(500)
        if is_running:
            socket.disconnectFromServer()
        socket.close()
        return is_running
    except Exception:
        return False

def create_server():
    """创建本地服务器"""
    try:
        server = QLocalServer()
        server.removeServer("ZToughAI")
        if not server.listen("ZToughAI"):
            return None
        return server
    except Exception:
        return None

# 检查是否已经有实例在运行
if is_running():
    app = QApplication(sys.argv)
    msg = QMessageBox()
    msg.setIcon(QMessageBox.Warning)
    msg.setWindowTitle("警告")
    msg.setText("智拓已经在运行中！请查看系统托盘。")
    msg.exec()
    sys.exit(0)

server = create_server()
if not server:
    app = QApplication(sys.argv)
    QMessageBox.critical(None, "错误", "无法创建本地服务器，程序将退出。")
    sys.exit(1)

if cfg.get(cfg.dpiScale) != "Auto":
    os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "0"
    os.environ["QT_SCALE_FACTOR"] = str(cfg.get(cfg.dpiScale))

# create application
app = QApplication(sys.argv)
app.setAttribute(Qt.AA_DontCreateNativeWidgetSiblings)

# internationalization
locale = cfg.get(cfg.language).value
translator = FluentTranslator(locale)
# proTranslator = ProTranslator(locale)
galleryTranslator = QTranslator()
galleryTranslator.load(locale, "app", ".", ":/app/i18n")

app.installTranslator(translator)
app.installTranslator(galleryTranslator)
# app.installTranslator(proTranslator)

# create main window
w = MainWindow()
w.show()

app.exec()
